#include "page4.h"          //设备报废
#include "ui_page4.h"
#include"src/mes.h"
#include<QMessageBox>
#include<QClipboard>

Page4::Page4(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Page4)
{
    ui->setupUi(this);
    initTableView();
    popMenu=new QMenu(ui->tableView);
    popMenu->addAction("复制",this,SLOT(slot_copyData()));
    connect(ui->tableView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotContextMenu(QPoint)));
}

void Page4::slotContextMenu(QPoint pos)
{
    auto index=ui->tableView->indexAt(pos);
    selectCurrentRow=index.row();
    selectCurrentColumn=index.column();
    if(index.isValid()){
        popMenu->exec(QCursor::pos());
    }
}

void Page4::slot_copyData()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(ui->tableView->model()->index(selectCurrentRow,selectCurrentColumn).data().toString());
}

Page4::~Page4()
{
    delete ui;
}

void Page4::on_pushButton_clicked()
{
    if(ui->account->value()==0){
        ui->errorMsg->setText("报废数量不能为0");
        return;
    }

    QString textReason=ui->textReason->toPlainText();
    if(textReason==""){
        ui->errorMsg->setText("带*号项目不能为空");
        return;
    }

    int account=ui->account->value();
    if(account==0){
        ui->errorMsg->setText("报废数量不能为0");
        return;
    }

    RepairTableModel *model=dynamic_cast<RepairTableModel *>(ui->tableView->model());
    auto i=model->check_state_map.begin();
    QString NO=model->index(i.key(),1,QModelIndex()).data().toString();
    QString workNumber=model->index(i.key(),3,QModelIndex()).data().toString();
    int useAccount=model->index(i.key(),4,QModelIndex()).data().toInt();

    if((useAccount-account)<0){
        ui->errorMsg->setText("报废数量不能大于保管者所拥有的数量");
        return;
    }

    if(!Mes::getInstance()->accountInsertUpdate(NO,workNumber,(useAccount-account),account,
                                                textReason,"")){
        return;
    }else{
        QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
        on_pushButton_2_clicked();
        ui->errorMsg->clear();
    }
}

void Page4::clearWidget()
{
    ui->NO->clear();
    ui->worNumber->clear();
    ui->account->setValue(0);
}

void Page4::initTableView()
{
    RepairTableModel *model=new RepairTableModel(this);
    model->setSqlist(sqlist);

    model->setTable("userForm");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setHeaderData(0,Qt::Horizontal,QString("勾选设备"));
    model->setHeaderData(1,Qt::Horizontal,QString("设备名称"));
    model->setHeaderData(2,Qt::Horizontal,QString("设备编号"));
    model->setHeaderData(3,Qt::Horizontal,QString("领用人工号"));
    model->setHeaderData(4,Qt::Horizontal,QString("拥有数量"));
    model->setHeaderData(5,Qt::Horizontal,QString("超期年限"));
    model->setHeaderData(6,Qt::Horizontal,QString("经办人工号"));
    model->setHeaderData(7,Qt::Horizontal,QString("领用时间"));
    model->setHeaderData(8,Qt::Horizontal,QString("存放地点"));
    model->select();
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略
}

void Page4::on_pushButton_3_clicked()     // 刷新
{
    sqlist.clear();
    sqlist<<ui->history->text().trimmed();
    initTableView();
}

void Page4::on_pushButton_2_clicked()
{
    sqlist.clear();
    sqlist<<ui->history->text().trimmed();
    if(ui->NO->text().trimmed()!="") sqlist<<QString("a.NO like '%%1%'").arg(ui->NO->text().trimmed());
    if(ui->name->text().trimmed()!="") sqlist<<QString("b.norms like '%%1%'").arg(ui->name->text().trimmed());
    if(ui->worNumber->text().trimmed()!="") sqlist<<QString("a.useWorkNumber='%1'").arg(ui->worNumber->text().trimmed());
    initTableView();
}

RepairTableModel::RepairTableModel(QObject *parent, QSqlDatabase db)
{

}

bool RepairTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(!index.isValid())
        return false;


    if (role == Qt::CheckStateRole && index.column() == checkColumn)
    {
        check_state_map.clear();
        check_state_map[index.row()] = (value == Qt::Checked ? Qt::Checked : Qt::Unchecked);return true;
    }
    else
        return QSqlTableModel::setData(index, value,role);
}

QVariant RepairTableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if (index.column() != checkColumn )
    {
        return QSqlTableModel::data(index, role);
    }
    switch(role)
    {
        case Qt::CheckStateRole:
        if(index.column() == checkColumn)
        {
            if (check_state_map.contains(index.row()))
            {
                return Qt::Checked;
            }

            return Qt::Unchecked;
        }
        default:
            return QVariant();
    }
    return QVariant();
}

Qt::ItemFlags RepairTableModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return 0;
    if (index.column() == checkColumn)
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;
    else
        return QSqlTableModel::flags(index);
    return  Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

QString RepairTableModel::selectStatement() const
{
    QString condition="";
    int i=0;
    for(QString tmp:sqlist){
        i++;
        if(i==1) continue;

        if(tmp==NULL){
            continue;
        }
        condition+=QString(" and ")+tmp;
    }

    QString sql=QString("select TOP %1 a.[NO],a.[NO],b.norms \
                        ,a.[useWorkNumber]    \
                        ,a.[useAccount]   \
                        ,a.[overTime] \
                        ,a.[agent]    \
                        ,a.[date] \
                        ,a.[station] from \
                        (select * from (select *    \
                        ,ROW_NUMBER() over(partition by NO,useWorkNumber order by NO) as rn \
                  from userForm)r where r.rn=1 and r.useAccount!=0)a inner join (select NO,norms from importForm)b \
            on a.NO=b.NO%2").arg(sqlist[0]).arg(condition);
    return sql;
}
